﻿<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller {

	public function __construct() {
		parent::__construct();
	}

	public function index() {
		$this->home();	

	}
	//==============================HOME FUNCTION=================================================
	public function home()
	{
		$this->load->model('model_books');
		$arr = $this->model_books->getList();
		
		// $query = $this->db->query("SELECT * FROM document");
		// $arr = $query->result_array();
		
		$list = array();

		foreach ($arr as $document) 
		{
			$book['id'] = $document['id_document'];
			$book['title'] = $document['name_document'];
			$book['cat'] = $document['name_cat'];
			$book['uploader'] = $document['username'];
			$book['author'] = $document['author'];
			if($book['author'] == '') $book['author'] = 'Chưa rõ';

			$this->load->helper('bookaccess');
			$linkcover = getCover($document['id_document']);
			$book['cover'] = $linkcover;

			array_push($list, $book);
		}
		$data['list'] = $list;

        //Get menu
        $data['template']['panel'] = true;
        $data['template']['menu'] = createMenu();
        if($this->is_login())
        	$data['template']['user'] = $this->session->userdata('username');

		$this->load->view('view_home', $data);
	}

	//==============================SEARCH FUNCTION=============================================
	public function search() {
		$text = $this->input->post('text');

		// Search Book
		$this->load->model('model_books');
		$list = $this->model_books->searchBook($text);
		$data['listBook'] = $list;

		// Search Tags
		$this->load->model('model_tags');
		$list = $this->model_tags->searchTag($text);
		$listbook = [];
		$this->load->helper('bookaccess');
        foreach($list as $book) 
        {
            if($book['author'] == '') $book['author'] = "Chưa rõ";

            $contentTable = getTableContent($book['id_document']);
            foreach($contentTable as $node) {
                if((string)$node['id'] == $book['id_chap']) {
                    $book['name_chap'] = $node['text'];
                    break;
                }
                $book['name_chap'] = 'Gợi ý chung';
            }
            array_push($listbook, $book);
        }
		$data['listTags'] = $listbook;

		// Search Location
		$this->load->model('model_tags');
		$list = $this->model_tags->searchLocation($text);
		$listbook = [];
		$this->load->helper('bookaccess');
        foreach($list as $book) 
        {
            if($book['author'] == '') $book['author'] = "Chưa rõ";

            $contentTable = getTableContent($book['id_document']);
            foreach($contentTable as $node) {
                if((string)$node['id'] == $book['id_chap']) {
                    $book['name_chap'] = $node['text'];
                    break;
                }
                $book['name_chap'] = 'Gợi ý chung';
            }
            array_push($listbook, $book);
        }
		$data['listLocal'] = $listbook;
		
		//Get menu
        $data['template']['menu'] = createMenu();
        if($this->is_login())
        	$data['template']['user'] = $this->session->userdata('username');

		$this->load->view('view_search', $data);
	}

	/**
	* ======================================================================================
	* ======================================================================================
	* Testing functions
	* ======================================================================================
	* ======================================================================================
	*/

	function getBookOpf($link) {

		//Get file and assign to object
		$xmlObject = @simplexml_load_file($link.'/content.opf');
		if ($xmlObject) return array('object' => $xmlObject, 'isOEBPS' => false);

		else $xmlObject = @simplexml_load_file($link.'/OEBPS/content.opf');
			if ($xmlObject) return array('object' => $xmlObject, 'isOEBPS' => true);
			else return -1;
	}

	function getCover($bookId) {
		$link = base_url().'assets/resource/'.$bookId;
		$temp = $this->getBookOpf($link);

		$xmlObject = $temp['object'];

		$bookCover = ''; //Store book cover and link to chapter

		if ($xmlObject != -1) //Check error from load file proccessing.
		{
			$number = 1;
			foreach ($xmlObject->manifest->children() as $child) {
				$attr = $child->attributes();
				if ($attr['id'] == 'cover' && $attr['media-type'] == 'image/jpeg') {
					if(!$temp['isOEBPS'])
						$bookCover = $link . '/' . $attr['href'];
					else $bookCover = $link . '/OEBPS/' . $attr['href'];
					break;
				}
			}
			if($bookCover == '') {
				$this->load->model('model_books');
				$book = $this->model_books->getBook($bookId);

				$letter = mb_substr($book['name_document'], 0, 1);
				if($letter == "Đ" || $letter == "đ") $letter = 'D';

				$bookCover = base_url() . 'assets/img/cover/cover'.$letter.'.jpg';
			}
			return $bookCover;
		}
		else return 'ERROR-BOOK';
	}

	function getBookInfo($bookId) {

		$link = base_url().'assets/resource/'.$bookId;
		$temp = $this->getBookOpf($link);

		$xmlObject = $temp['object'];

		$bookInfo = array('cover' => 'NO-IMAGE'); //Store book cover and link to chapter

		if ($xmlObject != -1) //Check error from load file proccessing.
		{
			$number = 1;
			foreach ($xmlObject->manifest->children() as $child) {
				$attr = $child->attributes();
				if ($attr['id'] == 'cover' && $attr['media-type'] == 'image/jpeg') {
					if(!$temp['isOEBPS'])
						$bookInfo['cover'] = '<img src="' . $link . '/' . $attr['href'] . '" />';
					else $bookInfo['cover'] = '<img src="' . $link . '/OEBPS/' . $attr['href'] . '" />';
				}
				if ($attr['media-type'] == 'application/xhtml+xml') {
					if(!$temp['isOEBPS'])
						$chap = array('chapter' => $attr['id'], 'href' => $link.'/'.$attr['href']);
					else
						$chap = array('chapter' => $attr['id'], 'href' => $link.'/OEBPS/'.$attr['href']);
					$bookInfo['chapter'.$number] = $chap;
					$number++;
				}
			}
			echo $bookInfo['cover'] . '<br><br>';
			foreach ($bookInfo as $chap => $arr) {
				if($chap != 'cover') {
					echo $arr['chapter'] . ' - ' . $arr['href'] . '<br>';
				}
			}
		}
		else echo 'Error to load file';
	}

/**
	* ======================================================================================
	* ======================================================================================
	* 
	* ======================================================================================
	* ======================================================================================
	*/
	

}